package com.backedserver.filter;

import com.common.global.JwtTokenException;
import com.common.global.CommonEnum;
import com.common.utils.JwtTokenUtils;
import com.common.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 自定义JwtTokenFilter
 *
 * @author johnny
 * @create 2020-07-18 下午8:28
 **/
@Component
@Slf4j
public class JwtTokenFilter extends OncePerRequestFilter {

    @Value("${systemParameters.exclude-url:/backend-admin/auth/cache2#/backend-admin/user/logout#/backend-admin/auth/cache#/backend-admin/auth/refreshToken#/backend-admin/auth/login#/backend-admin/swagger-ui.html#/backend-admin/webjars.*#/backend-admin/swagger-resources.*#/backend-admin/webjars.*#/backend-admin/csrf#}")
    private String excludeUrl;

    @Autowired
    @Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver resolver;


    @Value("${systemParameters.swagger2.enable}")
    private boolean swagger2Use;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        if (swagger2Use) {
            chain.doFilter(request, response);
            return;
        }
        if (StringUtils.isNotEmpty(excludeUrl)) {
            List<String> excludeUrlList = split(excludeUrl, "#");
            String requestUrI = request.getRequestURI();
            log.info("【requestUrI: {}】", requestUrI);
            if (CollectionUtils.isNotEmpty(excludeUrlList)) {
                for (String url : excludeUrlList) {
                    if(requestUrI.equals("/backend-admin/auth/refreshToken")){
                        System.out.println(requestUrI);
                    }
                    if (requestUrI.matches(url)) {
                        chain.doFilter(request, response);
                        return;
                    }
                }
            }
        }
        //跳过登录界面
        final String jwtToken = TokenUtils.getTokenFromRequest(request);
        log.info("jwtToken ： {}", jwtToken);
        String username;
        if (StringUtils.isNotEmpty(jwtToken)) {
            if (JwtTokenUtils.validate(jwtToken)) {
                username = JwtTokenUtils.getUserNameFromToken(jwtToken);
            } else {
                //未登录，告诉前台去登录
                resolver.resolveException(request, response, null, new JwtTokenException(CommonEnum.TOKEN_ERROR));
                return;
            }
            log.info("【请求账号:  {}】", username);
        } else {
            //未登录，告诉前台去登录
            resolver.resolveException(request, response, null, new JwtTokenException(CommonEnum.TOKEN_NOT_FIND));
            return;
        }
        chain.doFilter(request, response);
    }


    public static final List<String> split(String source, String separator) {
        if (source == null) {
            return null;
        }
        if ("".equals(source)) {
            return Collections.emptyList();
        }
        separator = separator == null ? "" : separator;

        String[] ids = source.split(separator);
        List<String> list = new ArrayList<String>();
        for (String s : ids) {
            try {
                list.add(s);
            } catch (NumberFormatException e) {
            }
        }
        return list;
    }
}